<template>
  <div class="personal-gender">
    <van-picker
      show-toolbar
      title="请选择性别"
      :columns="columns"
      :default-index="value"
      @confirm="onConfirm"
      @cancel="$emit('close')"
      @change="onPickerChange"
    />
  </div>
</template>

<script>
import { updateUserInfo } from '@/api/user' // 修改数据
export default {
  name: 'PersonalSex',
  components: {},
  data () {
    return {
      columns: ['女', '男'],
      localGender: this.value // 默认性别为女
    }
  },
  props: {
    value: {
      type: [Number, String],
      required: true
    },
    userId: {
      type: Number,
      required: true
    }
  },
  computed: {},
  watch: {},
  created () {},
  mounted () {},
  methods: {
    // 点击完成时
    async onConfirm () {
      // 网络慢速的情况下
      this.$toast.loading({
        message: '更新中...',
        forbidClick: true, // 禁止背景点击
        duration: 0 // 持续展示
      })
      try {
        const localGender = this.localGender
        await updateUserInfo({
          ...this.$store.state.user,
          sex: localGender, // 把当前表单里面的性别的索引 传给接口中的 sex 和 id
          id: this.userId
        })

        // 更新试图
        this.$emit('input', localGender)

        // 关闭弹层
        this.$emit('close')

        // 提示成功
        this.$toast.success('更新成功')
      } catch (err) {
        console.log(err)
        this.$toast.fail('更新失败，请稍后重试')
      }
    },
    // 绑定改变事件，当发生改变时 把当前改变的值的索引传给localGender
    onPickerChange (picker, value, index) {
      // console.log(value) // 值
      // console.log(index) // 索引
      this.localGender = index
    }
  }
}
</script>

<style scoped lang="less"></style>
